import cv2
import numpy as np

# 轮廓检测只能在二值化的图形中使用
img = cv2.imread("./img/color_recognize.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)
blue = cv2.bitwise_and(img[:, :, 0], binary)

# 轮廓检测
contours, _ = cv2.findContours(blue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# 标注所有轮廓点
# for contour in contours:
#     for item in contour:
#         x, y = item[0]
#         cv2.circle(img, [x, y], 2, color=(0, 0, 0), thickness=2)

# 轮廓的标注
for contour in contours:
    # boundingRect 从轮廓点中取出最大范围的矩形区域
    x, y, w, h = cv2.boundingRect(contour)
    cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 0), thickness=2)
    cv2.putText(img, "blue", (x, y), 0, 2, color=(0, 0, 0), thickness=2)

cv2.imshow("img", img)
cv2.waitKey(0)
